package com.oraking.android.jquery.korealaw.activity;

import java.util.ArrayList;
import java.util.Hashtable;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.HttpAuthHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.oraking.android.jquery.korealaw.R;
import com.oraking.android.jquery.korealaw.util.CmmFileUtil;
import com.oraking.android.jquery.korealaw.util.CmmHttpUtil;
import com.oraking.android.jquery.korealaw.util.CmmStr;
import com.oraking.android.jquery.korealaw.util.ParamList;

public class KoreaLawSearchCn extends Activity {
	
	Context mContext;
	WebView webView;
	ProgressDialog dial;	// ProgressBar
	Activity mActivity;
	
	String filePath;		// filePath 얻기
	
	// Handler 관련 상수 Start
	static final int PROGRESS_START = 0;
	static final int PROGRESS_STOP = 1;
	static final int HTML_GET = 2;
	// Handler 관련 상수 End

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    getResource();						// 리소스 구성
	    configueScreen();					// 화면 구성
	    
	    mHandler.sendEmptyMessage(HTML_GET);
	}
	
	// Data Communication 관련 Handler
	Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case PROGRESS_START:
				dial.show();
				break;
			case PROGRESS_STOP:
				dial.dismiss();
				break;
			case HTML_GET:
				getSavedHTML();
				break;
			default:
				break;
			}
		}
		
	};
	
	// 리소스 구성 관련 Method
	private void getResource(){
		mContext = getApplicationContext();						// Content 객체 얻기
        filePath = mContext.getFilesDir().getPath()+"/";		// filePath 얻기
        mActivity = KoreaLawSearchCn.this;

        // ProgressDialog 리소스 얻기 Start
		dial = new ProgressDialog(KoreaLawSearchCn.this);
        dial.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dial.setMessage("Wait a monent...");
        // ProgressDialog 리소스 얻기 End
	}
	
	// 화면 구성 관련 Method
	private void configueScreen(){
		setContentView(R.layout.korealawsearchcn);
		webView = (WebView)findViewById(R.id.webview);
		
		// webView Setting Start
		webView.setWebChromeClient(new ProxyWebChromeClient());
		webView.getSettings().setJavaScriptEnabled(true);						// Javascript 사용시 설정
		webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		webView.getSettings().setAllowFileAccess(true);
		webView.getSettings().setLightTouchEnabled(true);
		webView.getSettings().setBuiltInZoomControls(false);
		webView.setHorizontalScrollBarEnabled(false);
		webView.setVerticalScrollbarOverlay(true);								// 웹뷰 오른쪽 스크롤바 공간 없애기 설정
		
		webView.setWebChromeClient(new WebChromeClient() {
			public void onProgressChanged(WebView view, int progress) {
				mActivity.setProgress(progress * 100);
				if(progress == 100){
					mHandler.sendEmptyMessage(PROGRESS_STOP);
				}
			}
		});
		
		webView.setWebViewClient(new WebViewClient() {
			
			@Override
			public void doUpdateVisitedHistory(WebView view, String url,
					boolean isReload) {
				// TODO Auto-generated method stub
				super.doUpdateVisitedHistory(view, url, isReload);
			}

			@Override
			public void onFormResubmission(WebView view, Message dontResend,
					Message resend) {
				// TODO Auto-generated method stub
				// dontResend - The message to send if the browser should not resend
				// resend     - The message to send if the browser should resend data  
				super.onFormResubmission(view, dontResend, resend);
			}

			@Override
			public void onLoadResource(WebView view, String url) {
				// TODO Auto-generated method stub
				// 웹 페이지 리소스들을 로딩하면서 계속해서 호출된다.
				super.onLoadResource(view, url);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
				// 페이지 로딩이 끝났을 경우 호출 된다.
				super.onPageFinished(view, url);
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				// TODO Auto-generated method stub
				// 페이지 로딩이 시작될 경우 호출된다.
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public void onReceivedHttpAuthRequest(WebView view,
					HttpAuthHandler handler, String host, String realm) {
				// TODO Auto-generated method stub
				super.onReceivedHttpAuthRequest(view, handler, host, realm);
			}

			@Override
			public void onScaleChanged(WebView view, float oldScale,
					float newScale) {
				// TODO Auto-generated method stub
				super.onScaleChanged(view, oldScale, newScale);
			}

			@Override
			public void onTooManyRedirects(WebView view, Message cancelMsg,
					Message continueMsg) {
				// TODO Auto-generated method stub
				super.onTooManyRedirects(view, cancelMsg, continueMsg);
			}

			@Override
			public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
				// TODO Auto-generated method stub
				super.onUnhandledKeyEvent(view, event);
			}

			@Override
			public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
				// TODO Auto-generated method stub
				return super.shouldOverrideKeyEvent(view, event);
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				// TODO Auto-generated method stub
				// submit 버튼을 클릭시 호출되는 메소드
				Log.d("debug", "URL:" + url);
				return changeActvity(CmmHttpUtil.parseURL(url));
				//return super.shouldOverrideUrlLoading(view, url);
			}

			public void onReceivedError(WebView view, int errorCode, String description, String fallingUrl) {
				Toast.makeText(mActivity, "로딩오류" + description,Toast.LENGTH_SHORT).show();
			}
			
		});		
		// webView Setting End
	}
	
	// 저장된 HTML 가져오는 Mehtod
	private void getSavedHTML(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				mHandler.sendEmptyMessage(PROGRESS_START);
				
				/*
				CmmFileUtil.chkFile(filePath+CmmStr.CSS_PATH, CmmStr.CSS_PATH, CmmStr.CSS_FILES, KoreaLawSearchCn.this);
				CmmFileUtil.chkFile(filePath+CmmStr.THEMESWITCHER_PATH, CmmStr.THEMESWITCHER_PATH, CmmStr.THEMESWITCHER_FILES, KoreaLawSearchCn.this);
				CmmFileUtil.chkFile(filePath+CmmStr.JS_PATH, CmmStr.JS_PATH, CmmStr.JS_FILES, KoreaLawSearchCn.this);
				CmmFileUtil.chkFile(filePath+CmmStr.HTML_PATH, CmmStr.HTML_PATH, CmmStr.HTML_FILES, KoreaLawSearchCn.this);
				Log.d("debug", "file:///" +filePath+CmmStr.HTML_PATH + "koreaLawSearchCn.html");
				
				webView.loadUrl("file:///" +filePath+CmmStr.HTML_PATH + "koreaLawSearchCn.html");
				*/
				webView.loadUrl("file:///android_asset/www/koreaLawSearchCn.html");
			}
		}).start();
	}
	
	
	// Activity 전환
	private boolean changeActvity(ArrayList<Hashtable<String, String>> params){
		Intent mIntent = new Intent(KoreaLawSearchCn.this, KoreaLawSearchList.class);
		
		ParamList paramList = new ParamList();
		paramList.setList(params);
		mIntent.putExtra("params", paramList);
		startActivity(mIntent);
		return true;
	}
	
	// 뒤로가기 버튼을 눌렀을 경우 맨 첫페이지일때 이벤트 처리
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if(webView.canGoBack()){
			webView.goBack();
		}else{
			Toast.makeText(KoreaLawSearchCn.this, "첫 페이지입니다.", Toast.LENGTH_SHORT).show();
		}
	}
	
	public class ProxyWebChromeClient extends WebChromeClient {
	    public void onProgressChanged(WebView view, int newProgress) {
	    }
	}
}
